<?php

declare(strict_types=1);

namespace app\model;

use Carbon\Carbon;
use think\model\concern\SoftDelete;
use think\facade\Db;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $name 名称
 * @property string $code 别名
 * @property bool $serv_type 供应商类型(待完善：迁移现有供应商进入该体系)1话费 2 加油 3权益 4 外卖 5影票
 * @property string $api_config 接入api配置
 * @property float $gate_rate 通道费用比例 单位是百分之
 * @property int $order_count 订单数量
 * @property int $balance 余额 单位分  后续账户多的话迁移出另外一张表
 * @property bool $settle_type 结算方式 1 预充 2 返佣
 * @property float $settle_value 返佣比例或者预充折扣
 * @property string $updated_at 创建时间
 * @property string $created_at 更新时间
 * @property string $deleted_at
 * @property-read \app\model\OilOrder[] $oil_order
 * @property-read \app\model\CouponOrder[] $coupon_order
 * @property-read \app\model\CouponGoods[] $coupon_goods
 * @property-read \app\model\RechargeSupplierConfig $recharge_config
 * @property-read \app\model\OilCardOrder[] $oil_card_order
 * @property-read \app\model\PowerOrder[] $power_order
 * @property-read \app\model\MovieOrder[] $movie_order
 * @property-read \app\model\CouponProductChannel[] $coupon_products
 * @property string $type 供应商分类
 * @property int $agent_id 代理Id
 * @property-read mixed $last_time
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class BaseSupplier extends CommonModel
{


    use SoftDelete;

    const TYPE_TAKEOUT = 'takeout';//外卖

    const SETTLE_TYPE_PAYMENT = 1;
    const SETTLE_TYPE_COMMISSION = 2;
    // 结算方式
    protected $settleType = [1 => '预付', 2 => '返佣'];

    const ACTIVE_SERV_TYPE_PRODUCT_GATHER = -10; //总台添加活动供应商，匹对code https://inews.gtimg.com/newsapp_ls/0/14912187292/0.jiketuchuang.png


    //对应供应商的code 2022年5月18日
    const CODE_MEITUANMIAOSHA = 'meituanMiaoSha';
    const CODE_MEITUAN_DAODIAN = 'meituanDaoDian';//美团到店
    const CODE_MEITUAN_WAIMAI = 'meituanWaiMai'; //美团外卖
    const CODE_JUTUIKE = 'jutuike';
    const CODE_JINGCHONG = 'jingchong';          //鲸充(权益)
    const CODE_YIQIDA = 'yiqida';                //亿奇达权益
    const CODE_JINGDONGUNION = 'JingDongUnion';  //京东联盟
    const CODE_JUTUIKE_ACTIVITY = 'jutuikeActivity';  //聚推客活动---统一


    //代理商配置的对应的联盟账号
    const CODE_AGENT_MEITUAN_MEITUAN_PUB = 'meituan_pub';//美团联盟
    const CODE_AGENT_MEITUAN_MEITUAN_UNION = 'meituan_union';//分销联盟


    const CODE_PRODUCT = [
        self::CODE_MEITUANMIAOSHA => PRODUCT_SECKILL_SERV,
        self::CODE_MEITUAN_DAODIAN => PRODUCT_METUAN_SERV,
        self::CODE_MEITUAN_WAIMAI => PRODUCT_MEITUAN_TAKEOUT_SERV
    ];


    //供应商类型  note ：话费延用旧表 取值1 仅提前预留

    //  api_config 字段处理
    public function setApiConfigAttr($value, $data)
    {

        if (!$value) {
            return $value;
        }
        if (is_string($value)) return $value;

        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    public function getApiConfigAttr($value, $data)
    {
        if (empty($value)) {
            return [];
        }

        return json_decode($value, true);
    }

    /*
     滴滴加油订单
    */
    public function oilOrder()
    {
        return $this->hasMany(OilOrder::class, 'supplier_id', 'id');
    }

    /*
     权益订单
    */
    public function couponOrder()
    {
        return $this->hasMany(CouponOrder::class, 'supplier_id');
    }

    /*
    权益商品
    */
    public function couponGoods()
    {
        return $this->hasMany(CouponGoods::class, 'supplier_id');
    }

    /*
       权益商品
  */
    public function couponProducts()
    {
        return $this->hasMany(CouponProductChannel::class, 'supplier_id');
    }

    // 获取充值相关配置
    public function rechargeConfig()
    {
        return $this->hasOne(RechargeSupplierConfig::class, 'supplier_id');
    }

    /*
     油卡订单
    */
    public function oilCardOrder()
    {
        return $this->hasMany(OilCardOrder::class, 'supplier_id');
    }

    /*
    电费订单
    */
    public function powerOrder()
    {
        return $this->hasMany(PowerOrder::class, 'supplier_id');
    }

    /*
     * 影票订单
     */
    public function movieOrder()
    {
        return $this->hasMany(MovieOrder::class, 'supplier_id');
    }

    /**
     * 查询供应商最新余额
     */
    public static function getBalance($id, $type)
    {
        $info = Db::name('base_supplier')
            ->where('id', $id)
            ->whereNull('deleted_at')
            ->find();
        if (empty($info)) {
            return fail('供应商不存在');
        }

        try {
            $class = '\\api\\' . $type . '\\' . ucfirst($info['code']);
            if (!class_exists($class)) {
                return fail('该供应商不支持余额查询');
            }
            $model = new $class($info);
            if (!method_exists($model, 'queryAmount')) return fail('该供应商类型不支持余额查询');

            $balance = $model->queryAmount();
            if (false === $balance) {
                return fail($model->getError());
            }
            self::where('id', $id)
                ->update([
                    'balance' => $balance,
                ]);
        } catch (\Exception $e) {
            return fail('供应商代号有误：' . $e->getMessage());
        }

        return success('操作成功', [
            'balance' => $balance,
        ]);
    }

    //获取对应类型的供应商
    public function supplierList($type)
    {
        $list = self::where("serv_type", $type)->field("name,id")->select();
        return $list;
    }


    public function getLastTimeAttr()
    {
        $cache = cache('baseSupplierLast' . $this->id);
        if ($cache) return $cache;

        return Carbon::parse($this->created_at)->format('Y-m-d H:i:s');
    }

    /**
     *  获取供应商下拉框
     */
    public function getSelectRows()
    {
        return self::where("serv_type", PRODUCT_COUPON_SERV)->field("id,name")->select();
    }
}

